package com.wwt.server.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wwt.server.vo.ErrorCode;
import com.wwt.server.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *认证异常统一处理
 * 当用户请求了一个受保护的资源，但是用户没有通过认证，
 * 那么抛出异常，AuthenticationEntryPoint. Commence(..)就会被调用。
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        Result result = Result.fail(ErrorCode.AUTHENTICATION_ERROR.getMessage(), ErrorCode.AUTHENTICATION_ERROR.getCode());
        response.getWriter().print(new ObjectMapper().writeValueAsString(result));
    }
}
